<?php
namespace app\admin\controller;
use think\Log;

class Tools extends Base {
    
    
    /**
     * 上传
     *
     * @return \think\response\Json
     */
    public function upload_image() {
        
        // 获取表单上传文件 例如上传了001.jpg
        $files = $this->request->file('image');
        if(is_array($files)){
            $urls = [];
            foreach($files as $file){
                $result= $this->_upload($file);
                list($url,$msg) = $result;
                if($url){
                    $urls [] = $url;
                }
            }
            return json(
                [
                    'errno' => 0,
                    'data' => $urls
                ]);
        }else{
            // 移动到框架应用根目录/public/uploads/ 目录下
            $file = $files;
            if($file){
                $result= $this->_upload($file);
                list($url,$msg) = $result;
                if($url){
                    return json(
                        [
                            'errno' => 0,
                            'data' => [
                                $url
                            ]
                        ]);
                }else{
                    return json(
                        [
                            'errno' => 1,
                            'data' => [
                                $url
                            ]
                        ]);
                }
            }
        }
    }
    
    private function _upload($file){
        $size =10485760;// 1024 * 1024 * 10; 10m
        $path =  'uploads';
        $info = $file->validate(['size'=>$size,'ext'=>'jpg,jpeg,png,gif'])->rule('md5')->move(ROOT_PATH . 'public' . DS .$path);
        if($info){
            $url = DS.$path.DS.$info->getSaveName();
            $url = str_replace("\\", "/", $url);
            return [$url,'成功'];
        }else{
            // 上传失败获取错误信息
            //             return $this->returnResult(0,$file->getError());
            return [false,$file->getError()];
        }
    }
}